// 验证用户是否已登录
document.addEventListener('DOMContentLoaded', function() {
    // 从会话存储中获取用户信息
    const userInfo = sessionStorage.getItem('userInfo');
    
    // 检查用户信息是否存在
    if (!userInfo) {
        // 未登录，重定向到登录页面
        window.location.href = 'index.html';
    } else {
        // 已登录，解析用户信息并继续加载游戏
        try {
            const userData = JSON.parse(userInfo);
            console.log('用户已登录:', userData);
            // 准备按钮点击事件
            const prepareButton = document.getElementById('prepareButton');
            if (prepareButton) {
                prepareButton.addEventListener('click', async function() {
                    try {
                        const response = await fetch('/zhualaoer/ready', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            credentials: 'include' // 包含cookie信息
                        });
                        const result = await response.json();
                        
                        if (result.code === 200) {
                            // 隐藏准备按钮
                            prepareButton.style.display = 'none';
                        } else if (result.code === 500) {
                            // 返回首页
                            window.location.href = 'index.html';
                        } else {
                            // 其他错误提示
                            alert(result.message || '操作失败，请重试');
                        }
                    } catch (error) {
                        console.log('请求错误:', error);
                        alert('请求错误:', error);
                    }
                });
            }
            //添加出牌按钮点击事件
            const playButton = document.getElementById('playCardBtn');
            if (playButton) {
                playButton.addEventListener('click', async function() {
                    try {
                        //获取 id="myCards" 下选择的卡牌
                        const selectedCards = document.querySelectorAll('#myCards .selected');
                        // 检查是否选择了卡牌
                        if (selectedCards.length === 0) {
                            alert('请先选择一张卡牌');
                            return;
                        }
                        
                        // 将选择卡牌组装成参数，格式为：[{suit: 'SPADE', rank: '2'}, {suit: 'HEART', rank: '3'}]
                        const selectedCardsData = Array.from(selectedCards).map(card => ({
                            suit: convertSuitToEnum(card.dataset.suit),
                            rank: convertRankToEnum(card.dataset.rank)
                        }));
                        // 发送出牌请求
                        const response = await fetch('/zhualaoer/playAhand', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(selectedCardsData),
                            credentials: 'include' // 包含cookie信息
                        });
                        const result = await response.json();
                        
                        if (result.code === 200) {
                            // 隐藏出牌按钮
                            playButton.style.display = 'none';
                            
                            //选中的卡牌放到publicCards
                            let publicCards = document.getElementById('publicGameCards');
                            publicCards.innerHTML = '';
                            selectedCardsData.forEach(card => {
                                const suitInfo = convertSuit(card.suit);
                                const rankInfo = convertRank(card.rank);
                                publicCards.innerHTML += `<div class="card small-card front ${suitInfo.class}" data-rank="${rankInfo}" data-suit="${suitInfo.symbol}">${suitInfo.symbol}</div>`;
                      
                            });
                            
                            //移除卡牌点击事件
                            let myCards = document.getElementById('myCards');
                            const cards = myCards.querySelectorAll('.card');
                            //判断cards样式不是selected才加入cardData
                            const cardsData = Array.from(cards).filter(card => !card.classList.contains('selected')).map(card => ({
                                suit: convertSuitToEnum(card.dataset.suit),
                                rank: convertRankToEnum(card.dataset.rank)
                            }));
                            myCards.innerHTML = '';
                            cardsData.forEach(card => {
                                const suitInfo = convertSuit(card.suit);
                                const rankInfo = convertRank(card.rank);
                                myCards.innerHTML += `<div class="card front ${suitInfo.class}" data-rank="${rankInfo}" data-suit="${suitInfo.symbol}">${suitInfo.symbol}</div>`;
                      
                            });
                            document.getElementById('gameInfo').textContent = '等待其他玩家出牌';
                        } else if (result.code === 500) {
                            // 返回首页
                            window.location.href = 'index.html';
                        } else {
                            // 其他错误提示
                            alert(result.message || '操作失败，请重试');
                        }
                    } catch (error) {
                        alert('请求错误:', error);
                    }
                });
            }

            // 隐藏结算模块
            async function hideResultModal() {
                //请求下一局
                const response = await fetchNextRound();
                if(response){
                    //移除publicGameCards的所有子元素
                    let publicCards = document.getElementById('publicGameCards');
                    publicCards.innerHTML = '';
                    document.getElementById('result-modal').style.display = 'none';

                    //在发牌前调用
                    document.getElementById('loading-mask').style.display = '';
                }
            }
            
            // 绑定确认按钮事件
            document.querySelector('.confirm-btn').addEventListener('click', hideResultModal);
            
        } catch (error) {
            console.log('用户信息解析失败:', error);
            sessionStorage.removeItem('userInfo');
            window.location.href = 'index.html';
        }
    }
});

async function fetchNextRound(){
    try {
        const response = await fetch('/zhualaoer/nextRound');
        const result = await response.json();
        if (result.code==200 || result.code==400) {
            return true;
        }else if(result.code==500){
            // 未登录，重定向到登录页面
            window.location.href = 'index.html';
        }else{
            alert('获取结算信息失败:', result.message);
        } 
        console.log('获取结算信息失败:', result.message);
        return false;
    } catch (error) {
        console.log('获取结算信息接口异常:', error);
        return null;
    }
}